// BOSS巨大爆炸特效类
import { TimeManager } from './TimeManager.js';

export class BossExplosion {
    constructor(x, y, level = 1) {
        this.x = x;
        this.y = y;
        this.level = level;
        this.life = 4000; // 4秒超长爆炸效果
        this.maxLife = this.life;
        this.completed = false;
        
        // 爆炸阶段
        this.phase = 0; // 0: 初始冲击, 1: 主爆炸, 2: 冲击波扩散, 3: 余波
        this.phaseTimer = 0;
        
        // 主爆炸效果（超大范围）
        this.mainExplosionRadius = 0;
        this.maxMainRadius = 200 + level * 50; // 基础200，每级增加50
        
        // 多重冲击波
        this.shockwaves = [];
        this.initShockwaves();
        
        // 超多碎片
        this.debris = [];
        this.initDebris();
        
        // 密集火花
        this.sparks = [];
        this.initSparks();
        
        // 能量环系统
        this.energyRings = [];
        this.initEnergyRings();
        
        // 超大烟雾云
        this.smokeParticles = [];
        this.initSmokeParticles();
        
        // 次级爆炸点
        this.secondaryExplosions = [];
        this.initSecondaryExplosions();
        
        // 伤害区域
        this.damageRadius = 0;
        this.maxDamageRadius = 150 + level * 30; // 伤害范围
        this.damageActive = false;
        this.damageDealt = false; // 确保只造成一次伤害
    }
    
    initShockwaves() {
        // 创建多重冲击波
        for (let i = 0; i < 5; i++) {
            this.shockwaves.push({
                radius: 0,
                maxRadius: 300 + i * 50,
                speed: 2 + i * 0.5,
                delay: i * 200,
                alpha: 0.8 - i * 0.15,
                active: false
            });
        }
    }
    
    initDebris() {
        // 创建大量机身碎片
        for (let i = 0; i < 40; i++) {
            const angle = (i / 40) * Math.PI * 2;
            const speed = Math.random() * 8 + 4;
            this.debris.push({
                x: this.x,
                y: this.y,
                vx: Math.cos(angle) * speed,
                vy: Math.sin(angle) * speed,
                rotation: Math.random() * Math.PI * 2,
                rotationSpeed: (Math.random() - 0.5) * 0.5,
                size: Math.random() * 15 + 8,
                color: ['#ff0000', '#ff6666', '#cc0000', '#990000', '#ffaa00'][Math.floor(Math.random() * 5)],
                life: this.maxLife * 0.8,
                maxLife: this.maxLife * 0.8
            });
        }
    }
    
    initSparks() {
        // 创建密集火花效果
        for (let i = 0; i < 60; i++) {
            const angle = Math.random() * Math.PI * 2;
            const speed = Math.random() * 12 + 6;
            this.sparks.push({
                x: this.x,
                y: this.y,
                vx: Math.cos(angle) * speed,
                vy: Math.sin(angle) * speed,
                life: Math.random() * 1500 + 800,
                maxLife: Math.random() * 1500 + 800,
                brightness: Math.random() * 0.8 + 0.2,
                color: ['#ffffff', '#ffff00', '#ffaa00', '#ff6600', '#ff0000'][Math.floor(Math.random() * 5)]
            });
        }
    }
    
    initEnergyRings() {
        // 创建多层能量冲击环
        for (let i = 0; i < 8; i++) {
            this.energyRings.push({
                radius: 0,
                maxRadius: 100 + i * 35,
                speed: 1.5 + i * 0.5,
                alpha: 0.9 - i * 0.1,
                delay: i * 150,
                active: false,
                color: i % 3 === 0 ? [255, 0, 0] : i % 3 === 1 ? [255, 165, 0] : [255, 255, 0]
            });
        }
    }
    
    initSmokeParticles() {
        // 创建超大烟雾云
        for (let i = 0; i < 50; i++) {
            const angle = Math.random() * Math.PI * 2;
            const speed = Math.random() * 3 + 1;
            this.smokeParticles.push({
                x: this.x + (Math.random() - 0.5) * 100,
                y: this.y + (Math.random() - 0.5) * 100,
                vx: Math.cos(angle) * speed,
                vy: Math.sin(angle) * speed - 2,
                size: Math.random() * 40 + 20,
                maxSize: Math.random() * 80 + 60,
                alpha: 0.8,
                life: this.maxLife,
                maxLife: this.maxLife
            });
        }
    }
    
    initSecondaryExplosions() {
        // 创建多个次级爆炸点
        for (let i = 0; i < 8; i++) {
            const angle = (i / 8) * Math.PI * 2;
            const distance = 60 + Math.random() * 40;
            this.secondaryExplosions.push({
                x: this.x + Math.cos(angle) * distance,
                y: this.y + Math.sin(angle) * distance,
                radius: 0,
                maxRadius: 60 + Math.random() * 30,
                delay: 300 + i * 200,
                active: false,
                alpha: 0.8
            });
        }
    }
    
    update(deltaTime) {
        this.life = TimeManager.updateTimer(this.life, deltaTime);
        this.phaseTimer += deltaTime;
        
        // 更新爆炸阶段
        if (this.phaseTimer < 500) {
            this.phase = 0; // 初始冲击
        } else if (this.phaseTimer < 1500) {
            this.phase = 1; // 主爆炸
        } else if (this.phaseTimer < 2500) {
            this.phase = 2; // 冲击波扩散
        } else {
            this.phase = 3; // 余波
        }
        
        // 更新主爆炸
        if (this.phase <= 1) {
            this.mainExplosionRadius = Math.min(
                this.maxMainRadius,
                (this.phaseTimer / 1500) * this.maxMainRadius
            );
        }
        
        // 更新伤害区域
        if (this.phase <= 2 && !this.damageDealt) {
            this.damageActive = true;
            this.damageRadius = Math.min(
                this.maxDamageRadius,
                (this.phaseTimer / 2000) * this.maxDamageRadius
            );
        } else if (this.phase > 2) {
            this.damageActive = false;
        }
        
        // 更新冲击波
        for (let wave of this.shockwaves) {
            if (this.phaseTimer > wave.delay && !wave.active) {
                wave.active = true;
            }
            if (wave.active) {
                wave.radius += wave.speed * (deltaTime / 16.67);
            }
        }
        
        // 更新次级爆炸
        for (let explosion of this.secondaryExplosions) {
            if (this.phaseTimer > explosion.delay && !explosion.active) {
                explosion.active = true;
            }
            if (explosion.active) {
                explosion.radius += 3 * (deltaTime / 16.67);
                explosion.alpha *= Math.pow(0.97, deltaTime / 16.67);
            }
        }
        
        // 更新碎片
        for (let debris of this.debris) {
            debris.x += debris.vx * (deltaTime / 16.67);
            debris.y += debris.vy * (deltaTime / 16.67);
            debris.vy += 0.1 * (deltaTime / 16.67); // 重力
            debris.rotation += debris.rotationSpeed * (deltaTime / 16.67);
            debris.life = TimeManager.updateTimer(debris.life, deltaTime);
        }
        
        // 更新火花
        for (let spark of this.sparks) {
            spark.x += spark.vx * (deltaTime / 16.67);
            spark.y += spark.vy * (deltaTime / 16.67);
            spark.vx *= Math.pow(0.95, deltaTime / 16.67);
            spark.vy *= Math.pow(0.95, deltaTime / 16.67);
            spark.life = TimeManager.updateTimer(spark.life, deltaTime);
        }
        
        // 更新能量环
        for (let ring of this.energyRings) {
            if (this.phaseTimer > ring.delay) {
                ring.active = true;
                ring.radius += ring.speed * (deltaTime / 16.67);
            }
        }
        
        // 更新烟雾
        for (let smoke of this.smokeParticles) {
            smoke.x += smoke.vx * (deltaTime / 16.67);
            smoke.y += smoke.vy * (deltaTime / 16.67);
            smoke.size += (smoke.maxSize - smoke.size) * 0.01 * (deltaTime / 16.67);
            smoke.alpha *= Math.pow(0.99, deltaTime / 16.67);
            smoke.life = TimeManager.updateTimer(smoke.life, deltaTime);
        }
        
        // 检查爆炸完成
        if (TimeManager.isTimeUp(this.life)) {
            this.completed = true;
        }
        
        return !this.completed;
    }
    
    // 检查玩家是否在伤害区域内
    checkPlayerDamage(player) {
        if (!this.damageActive || this.damageDealt) return false;
        
        const dx = player.x + player.width/2 - this.x;
        const dy = player.y + player.height/2 - this.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        if (distance <= this.damageRadius) {
            this.damageDealt = true; // 标记已造成伤害
            return true;
        }
        return false;
    }
    
    render(ctx) {
        ctx.save();
        
        // 渲染烟雾（背景层）
        this.renderSmokeParticles(ctx);
        
        // 渲染冲击波
        this.renderShockwaves(ctx);
        
        // 渲染次级爆炸
        this.renderSecondaryExplosions(ctx);
        
        // 渲染主爆炸
        if (this.phase <= 1) {
            this.renderMainExplosion(ctx);
        }
        
        // 渲染能量环
        this.renderEnergyRings(ctx);
        
        // 渲染碎片
        this.renderDebris(ctx);
        
        // 渲染火花
        this.renderSparks(ctx);
        
        // 渲染强烈闪光
        if (this.phase === 0) {
            this.renderFlash(ctx);
        }
        
        // 渲染伤害区域指示（调试用）
        if (this.damageActive) {
            this.renderDamageArea(ctx);
        }
        
        ctx.restore();
    }
    
    renderMainExplosion(ctx) {
        const progress = this.mainExplosionRadius / this.maxMainRadius;
        const alpha = 1 - progress * 0.5;
        const safeRadius = Math.max(0, this.mainExplosionRadius);
        
        if (safeRadius <= 0) return;
        
        // 超大火球
        const outerGradient = ctx.createRadialGradient(
            this.x, this.y, 0,
            this.x, this.y, safeRadius
        );
        outerGradient.addColorStop(0, `rgba(255, 255, 255, ${alpha})`);
        outerGradient.addColorStop(0.2, `rgba(255, 255, 100, ${alpha * 0.9})`);
        outerGradient.addColorStop(0.4, `rgba(255, 165, 0, ${alpha * 0.8})`);
        outerGradient.addColorStop(0.7, `rgba(255, 0, 0, ${alpha * 0.6})`);
        outerGradient.addColorStop(1, 'rgba(150, 0, 0, 0)');
        
        ctx.fillStyle = outerGradient;
        ctx.beginPath();
        ctx.arc(this.x, this.y, safeRadius, 0, Math.PI * 2);
        ctx.fill();
        
        // 内层核心
        const coreRadius = Math.max(0, safeRadius * 0.6);
        if (coreRadius > 0) {
            const coreGradient = ctx.createRadialGradient(
                this.x, this.y, 0,
                this.x, this.y, coreRadius
            );
            coreGradient.addColorStop(0, `rgba(255, 255, 255, ${alpha})`);
            coreGradient.addColorStop(0.5, `rgba(255, 255, 200, ${alpha * 0.8})`);
            coreGradient.addColorStop(1, `rgba(255, 165, 0, ${alpha * 0.4})`);
            
            ctx.fillStyle = coreGradient;
            ctx.beginPath();
            ctx.arc(this.x, this.y, coreRadius, 0, Math.PI * 2);
            ctx.fill();
        }
    }
    
    renderShockwaves(ctx) {
        for (let wave of this.shockwaves) {
            if (wave.active && wave.radius < wave.maxRadius && wave.radius > 0) {
                const alpha = wave.alpha * (1 - wave.radius / wave.maxRadius);
                const safeRadius = Math.max(0, wave.radius);
                
                ctx.strokeStyle = `rgba(255, 100, 0, ${alpha})`;
                ctx.lineWidth = 6;
                ctx.beginPath();
                ctx.arc(this.x, this.y, safeRadius, 0, Math.PI * 2);
                ctx.stroke();
                
                // 内层冲击波
                const innerRadius = Math.max(0, safeRadius - 10);
                if (innerRadius > 0) {
                    ctx.strokeStyle = `rgba(255, 255, 100, ${alpha * 0.6})`;
                    ctx.lineWidth = 3;
                    ctx.beginPath();
                    ctx.arc(this.x, this.y, innerRadius, 0, Math.PI * 2);
                    ctx.stroke();
                }
            }
        }
    }
    
    renderSecondaryExplosions(ctx) {
        for (let explosion of this.secondaryExplosions) {
            if (explosion.active && explosion.alpha > 0.01) {
                const safeRadius = Math.max(0, explosion.radius);
                if (safeRadius <= 0) continue;
                
                const gradient = ctx.createRadialGradient(
                    explosion.x, explosion.y, 0,
                    explosion.x, explosion.y, safeRadius
                );
                gradient.addColorStop(0, `rgba(255, 255, 255, ${explosion.alpha})`);
                gradient.addColorStop(0.4, `rgba(255, 165, 0, ${explosion.alpha * 0.8})`);
                gradient.addColorStop(1, 'rgba(255, 0, 0, 0)');
                
                ctx.fillStyle = gradient;
                ctx.beginPath();
                ctx.arc(explosion.x, explosion.y, safeRadius, 0, Math.PI * 2);
                ctx.fill();
            }
        }
    }
    
    renderEnergyRings(ctx) {
        for (let ring of this.energyRings) {
            if (ring.active && ring.radius < ring.maxRadius && ring.radius > 0) {
                const alpha = ring.alpha * (1 - ring.radius / ring.maxRadius);
                const safeRadius = Math.max(0, ring.radius);
                
                ctx.strokeStyle = `rgba(${ring.color[0]}, ${ring.color[1]}, ${ring.color[2]}, ${alpha})`;
                ctx.lineWidth = 4;
                ctx.beginPath();
                ctx.arc(this.x, this.y, safeRadius, 0, Math.PI * 2);
                ctx.stroke();
            }
        }
    }
    
    renderDebris(ctx) {
        for (let debris of this.debris) {
            if (!TimeManager.isTimeUp(debris.life)) {
                const alpha = debris.life / debris.maxLife;
                
                ctx.save();
                ctx.translate(debris.x, debris.y);
                ctx.rotate(debris.rotation);
                
                ctx.fillStyle = debris.color + Math.floor(alpha * 255).toString(16).padStart(2, '0');
                ctx.fillRect(-debris.size/2, -debris.size/2, debris.size, debris.size);
                
                ctx.restore();
            }
        }
    }
    
    renderSparks(ctx) {
        for (let spark of this.sparks) {
            if (!TimeManager.isTimeUp(spark.life)) {
                const alpha = spark.life / spark.maxLife * spark.brightness;
                
                ctx.fillStyle = spark.color + Math.floor(alpha * 255).toString(16).padStart(2, '0');
                ctx.fillRect(spark.x - 2, spark.y - 2, 4, 4);
                
                // 拖尾效果
                ctx.strokeStyle = spark.color + Math.floor(alpha * 128).toString(16).padStart(2, '0');
                ctx.lineWidth = 2;
                ctx.beginPath();
                ctx.moveTo(spark.x, spark.y);
                ctx.lineTo(spark.x - spark.vx * 0.8, spark.y - spark.vy * 0.8);
                ctx.stroke();
            }
        }
    }
    
    renderSmokeParticles(ctx) {
        for (let smoke of this.smokeParticles) {
            if (!TimeManager.isTimeUp(smoke.life) && smoke.alpha > 0.01) {
                const safeSize = Math.max(0, smoke.size);
                
                if (safeSize > 0) {
                    const gradient = ctx.createRadialGradient(
                        smoke.x, smoke.y, 0,
                        smoke.x, smoke.y, safeSize
                    );
                    gradient.addColorStop(0, `rgba(100, 100, 100, ${smoke.alpha})`);
                    gradient.addColorStop(0.7, `rgba(80, 80, 80, ${smoke.alpha * 0.6})`);
                    gradient.addColorStop(1, 'rgba(60, 60, 60, 0)');
                    
                    ctx.fillStyle = gradient;
                    ctx.beginPath();
                    ctx.arc(smoke.x, smoke.y, safeSize, 0, Math.PI * 2);
                    ctx.fill();
                }
            }
        }
    }
    
    renderFlash(ctx) {
        // 超强闪光
        if (this.phaseTimer < 300) {
            const alpha = 1.0 * (1 - this.phaseTimer / 300);
            const flashRadius = Math.max(0, this.maxMainRadius * 2.5);
            
            if (flashRadius > 0) {
                ctx.fillStyle = `rgba(255, 255, 255, ${alpha})`;
                ctx.beginPath();
                ctx.arc(this.x, this.y, flashRadius, 0, Math.PI * 2);
                ctx.fill();
            }
        }
    }
    
    renderDamageArea(ctx) {
        // 伤害区域可视化（半透明红圈）
        if (this.damageRadius > 0) {
            ctx.strokeStyle = 'rgba(255, 0, 0, 0.3)';
            ctx.lineWidth = 3;
            ctx.setLineDash([10, 5]);
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.damageRadius, 0, Math.PI * 2);
            ctx.stroke();
            ctx.setLineDash([]);
        }
    }
}